package alarm.imp;

import alarm.ZTextField;
import commons.util.PropertiesUtil;
import org.apache.logging.log4j.Logger;

import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.Document;
import java.util.HashMap;
import java.util.Map;

public class ZtextDo {
    private String firstString;
    private String saveFileString;
    private String relativePath;
    private String KeyName;
    private ZTextField zf;
    public ZtextDo(String firstString, String saveFileString, String relativePath, String keyName) {
        this.firstString = firstString;
        this.saveFileString = saveFileString;
        this.relativePath = relativePath;
        this.KeyName = keyName;
        this.zf = zf;
    }
    public String getFirstString() {
        return firstString;
    }

    public void setFirstString(String firstString) {
        this.firstString = firstString;
    }

    public String getSaveFileString() {
        return saveFileString;
    }

    public void setSaveFileString(String saveFileString) {
        this.saveFileString = saveFileString;
    }

    public String getRelativePath() {
        return relativePath;
    }

    public void setRelativePath(String relativePath) {
        this.relativePath = relativePath;
    }

    public String getKeyName() {
        return KeyName;
    }

    public void setKeyName(String keyName) {
        KeyName = keyName;
    }

    public ZTextField getZf() {
        return zf;
    }

    public void setZf(ZTextField zf) {
        this.zf = zf;
    }



    private void doChange(String value) {
        Map<String, String> map = new HashMap<>();
        map.put(KeyName,value);
        PropertiesUtil.setValueByFileName(map, saveFileString, relativePath);
    }

    public String getTextName() {
        String name = "".equals(PropertiesUtil.getValueFromFileNameAndKey(KeyName, saveFileString, relativePath))
                ? "0"
                : PropertiesUtil.getValueFromFileNameAndKey(KeyName, saveFileString, relativePath);
        return name;
    }
    public void addWriterFactorListener(ZTextField zf, Logger LOGGER){
        Document dc =  zf.getDocument();
        dc.addDocumentListener(new DocumentListener() {
            @Override
            public void insertUpdate(DocumentEvent e) {
                doChange(zf.getText());
            }
            @Override
            public void removeUpdate(DocumentEvent e) {
                doChange(zf.getText());
            }
            @Override
            public void changedUpdate(DocumentEvent e) {
                LOGGER.info("What?");
            }

        });

    }
}
